import React, {Component} from 'react'
import Dimensions from 'react-dimensions'
import {fetchData} from '../../components/AjaxConsumer'
import { AutoComplete,
    Modal,
    Button,
    Input,
    Select,
    InputNumber,
    Upload,
    Form,
    Row,
    Col,
    Icon,
    Radio,
    notification,
    TreeSelect,
    message,
    DatePicker,
    TimePicker
} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
import moment from 'moment';

export default class ControlForm extends React.Component {
    constructor(props) {
        super(props);
        //是否允许表单提交的flag变量
        this.submitFlag = true;
        this.state = {
            // 这是远程下拉框拿到的值（联动）
             provinceData: [{dicCode:'Zhejiang',dicName:'浙江'}, {dicCode:'Jiangsu',dicName:'江苏'}],
             cityData: [],
             SelectAutoCompleteRemoteData:[],
            //初始值和最后拿到的值都放在这里面
            formValues: {
                inputValue: '123456',
                selectValue: 'value2',
                timePickerValue:'12:58:25',
                datePickerValue: '2017/05/11',
                radioGroupValue: 4,
                province: 'Zhejiang',
                city: '',
                selectRemote:'',
                inputNumberValue:'',
                email:'',
            },
            //每个输入框校验样式flag
            validateStatusInput: '',
            validateStatusProvince: '',
            validateStatusCity: '',
            validateStatusInputNumber:'',
            validateStatusEmail: '',
            validateStatusRemote: '',
        };
    }
    pushValueInFromValues = (tagName, item) => {
        let tempFormValues = this.state.formValues;
        tempFormValues[tagName] = item;
        this.setState({ formValues: tempFormValues });
    }

    //各个输入框的的change事件
    handleInputChange = (e) => {
        console.log('InputChangeValue',e.target.value)
        //校验样式
        if(e.target.value == '' || e.target.value == null){
            this.setState({validateStatusInput:'error'})
        } else {
            this.setState({validateStatusInput:'success'})
        }
        this.pushValueInFromValues('inputValue',e.target.value);
    }
    handleSelectChange = (value) => {
        console.log('SelectValue',value)
        this.pushValueInFromValues('selectValue',value);
    }
    handleTimePickerChange = (time,timeString) => {
        console.log('timePickerChange',timeString)
        this.pushValueInFromValues('timePickerValue',timeString);
    }
    handleDatePickerChange = (date, dateString) => {
        console.log(dateString);
        this.pushValueInFromValues('datePickerValue',dateString);
    }
    handleRadioGroupChange = (e) => {
        console.log('RadioGroupChange', e.target.value);
        this.pushValueInFromValues('RadioGroupValue',e.target.value);
    }
    handleProvinceChange = (value) => {
        console.log( 'handleProvinceChange', value );
        //校验样式
        if(value == '' || value == null){
            this.setState({validateStatusProvince:'error'})
        } else {
            this.setState({validateStatusProvince:'success'})
        }
        this.pushValueInFromValues('province',value);
        const options= {
            url: '/getSelectData',
            type: 'get',
            condition:{
                // id: rowObj.resroleId
            }
        };
        fetchData(this,options,(res)=>{
            let resData = res.data;
            //清空原来选择的值
            let formValues = this.state.formValues;
            formValues.city = null;
            this.setState({
                cityData: resData,
                formValues: formValues
            })
        })
    } 
    onSecondCityChange = (value) => {
        console.log( 'onSecondCityChange', value );
        //校验样式
        if(value == '' || value == null){
            this.setState({validateStatusCity:'error'})
        } else {
            this.setState({validateStatusCity:'success'})
        }
        this.pushValueInFromValues('city',value);
    }
    handleSelectAutoCompleteRemoteSearch = (value) => {
        console.log('selectAutoCompleteRemoteSearch',value)
        //当回退掉所有输入值的时候，不发送ajax
        if (value != ''){
            const options= {
                // url: '/getSelectData2/'+value,  后台调用使用
                url: '/getSelectData2/1',
                condition:{},
                type: 'get', 
            };
            fetchData(this, options, (res) => {
                //放到远程下拉框的state中，再去渲染
                this.setState({ SelectAutoCompleteRemoteData:res.data })
            });
        }
    }
    handleSelectAutoCompleteRemoteChange = (value) => {
        console.log('selectAutoCompleteRemoteChange',value)
        this.setState({validateStatusRemote:'success'})
        this.pushValueInFromValues('selectRemote',value)
    }
    handleInputNumberChange = (e) => {
        //数字校验
        const { value } = e.target;
        const reg = /^-?(?:[1-9][0-9]*|0)(?:.[0-9]+)?$/
        if ((!isNaN(value) && reg.test(value)) || value === '' || value === '-') {
            console.log('InputNumberChangeValue',e.target.value)
            // 校验样式
            if(e.target.value == '' || e.target.value == null){
                this.setState({validateStatusInputNumber:'error'})
            } else {
                this.setState({validateStatusInputNumber:'success'})
            }
            this.pushValueInFromValues('inputNumberValue',e.target.value);
        }
    }
    handleEmailChange = (e) => {
        const { value } = e.target;
        const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (reg.test(value)) {
            // 校验样式
            this.setState({validateStatusEmail:'success'})
        } else {
            this.setState({validateStatusEmail:'error'})
        }
        console.log('emailChangeValue',value)
        //不管正确还是错误都存入state中，在点击submit的时候还需要进行校验
        this.pushValueInFromValues('email',value);
    }
    //表单提交
    handleSubmit = () => {
        let res = this.state.formValues
        //输出格式控制，若有undefined则转换为空('')
        for( let item in res){
            if(!res[item]){
                res[item] = ''
            }
        }
        console.log('result of form is :',res)
        //校验
        this.submitFlag = true;
        if(res.inputValue == '' || res.inputValue == null){
            this.setState({validateStatusInput:'error'})
            //把表单提交flag设置为false
            this.submitFlag = false;
        } else {
            this.setState({validateStatusInput:'success'})
        }
        if(res.province == '' || res.province == null){
            this.setState({validateStatusProvince:'error'})
            this.submitFlag = false;
        } else {
            this.setState({validateStatusProvince:'success'})
        }
        if(res.city == '' || res.city == null){
            this.setState({validateStatusCity:'error'})
            this.submitFlag = false;
        } else {
            this.setState({validateStatusCity:'success'})
        } 
        if (res.selectRemote == '' || res.selectRemote == null){
            this.setState({validateStatusRemote:'error'})
            this.submitFlag = false;
        } else {
            this.setState({validateStatusRemote:'success'})
        }
        if (res.inputNumberValue == '' || res.inputNumberValue == null){
            this.setState({validateStatusInputNumber:'error'})
            this.submitFlag = false;
        } else {
            this.setState({validateStatusInputNumber:'success'})
        }
        const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (!emailReg.test(res.email)) {
            this.setState({validateStatusEmail:'error'})
            this.submitFlag = false;
        } else {
            this.setState({validateStatusEmail:'success'})
        }
        //若submitFlag没有被置为false，则让表单进行提交
        if(this.submitFlag == true){
            const options= {
                url: '/actionUrl',
                type: 'post',
                condition:{
                    res
                }
            };
            fetchData(this,options,(res)=>{
                //回调函数
            })
        } else {
            console.log('error!  请先完成表单')
        }
    }
    handResetForm = () => {
        let formValues = this.state.formValues;
        let tempFormValues = {};
        for (let e in formValues){
            tempFormValues[e] = null
        }
        
        this.setState({
            provinceData: [{dicCode:'Zhejiang',dicName:'浙江'}, {dicCode:'Jiangsu',dicName:'江苏'}],
            cityData: [],
            SelectAutoCompleteRemoteData:[],
            formValues: tempFormValues,
            validateStatusInput: '',
            validateStatusProvince: '',
            validateStatusCity: '',
            validateStatusInputNumber:'',
            validateStatusEmail:'',
            validateStatusRemote: '',
        })
    }

    //若有初始数据，则在此加载并且填充
    componentDidMount() {
         const options= {
            url: '/getSelectData',
            type: 'get',
            condition:{
                // id: rowObj.resroleId
            }
        };
        fetchData(this,options,(res)=>{
            let resData = res.data;
            //清空原来选择的值
            let formValues = this.state.formValues;
            formValues.city = null;
            this.setState({
                cityData: resData,
                formValues: formValues
            })
        })
    }
    

    render() {
        let provinceOptions = []
        if(this.state.provinceData instanceof Array){
            provinceOptions = this.state.provinceData.map(province => <Option key={province.dicCode} value={province.dicCode}>{province.dicName}</Option>);
        }
        let cityOptions = []
        if(this.state.cityData instanceof Array) {
            cityOptions= this.state.cityData.map(city => <Option key={city.dicCode} value={city.dicCode}>{city.dicName}</Option>);
        }
        let selectRemoteChildren = [];
        let childrenList = this.state.SelectAutoCompleteRemoteData ? this.state.SelectAutoCompleteRemoteData : [];
        selectRemoteChildren = childrenList.map(d => <Option key={d.key} value={d.key} dataSearchVal={d.value}>{d.value}</Option>);
        return (
            <div style={{
                border: '1px solid #d3d3d3',
                backgroundColor: '#fff',
                margin:'0px 5px 10px 5px',
                padding:'20px 10px',
            }}>
                <Row style={{marginBottom:'20px'}}>
                    <Col span={2}>
                        <label htmlFor="input" className="infoForm_label" >输入框:</label>
                    </Col>
                    <Col span={4}>
                    <FormItem
                        validateStatus={this.state.validateStatusInput}
                        hasFeedback
                        help={this.state.validateStatusInput == 'error' ? '请填写输入框' : ''}
                    >
                        <Input
                            id='input'
                            name='input'
                            disabled={false}
                            placeholder="请输入"
                            onChange={this.handleInputChange}
                            value={this.state.formValues.inputValue}
                            defaultValue={this.state.formValues.inputValue}
                        />
                    </FormItem>
                    </Col>
                    <Col span={2} >
                        <label htmlFor="select" className="infoForm_label" >下拉框:</label>
                    </Col>
                    <Col span={4}>
                        <FormItem
                            validateStatus={''}
                            hasFeedback
                            required={true}
                        >
                            <Select size={'default'}
                                    id='select'
                                    name='select'
                                    disabled={false}
                                    style={{width:'120px'}}
                                    placeholder="请输入"
                                    onChange={this.handleSelectChange}
                                    showSearch
                                    value={this.state.formValues.selectValue}
                                    defaultValue={this.state.formValues.selectValue}
                            >
                                <Option value={'value1'}>展示名1aaa</Option>
                                <Option value={'value2'}>展示名2AAA</Option>
                                <Option value={'value3'}>展示名3ccc</Option>
                                <Option value={'value4'}>展示名4</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span={2}>
                        <label htmlFor="TimePicker" className="infoForm_label" >时间选框:</label>
                    </Col>
                    <Col span={4}>
                        <TimePicker
                            id='TimePicker'
                            name='TimePicker'
                            disabled={false}
                            format={'HH:mm:ss'}
                            onChange={this.handleTimePickerChange}
                            value={this.state.formValues.timePickerValue?moment(this.state.formValues.timePickerValue, 'HH:mm:ss'):null}
                        />
                    </Col>
                    <Col span={2} >
                        <label htmlFor="DatePicker" className="infoForm_label" >日期选框:</label>
                    </Col>
                    <Col span={4}>
                        <DatePicker
                            id='DatePicker'
                            name='DatePicker'
                            disabled={false}
                            format={'YYYY/MM/DD'}
                            onChange={this.handleDatePickerChange}
                            value={this.state.formValues.datePickerValue?moment(this.state.formValues.datePickerValue, 'YYYY/MM/DD'):null}
                        />
                    </Col>
                </Row>
                <Row >
                    <Col span={2}  >
                        <label htmlFor="RadioGroup" className="infoForm_label" >单选按钮:</label>
                    </Col>
                    <Col span={10}>
                        <RadioGroup
                            id='RadioGroup'
                            name='RadioGroup'
                            required={true}
                            onChange={this.handleRadioGroupChange}
                            value={this.state.formValues.radioGroupValue}
                            defaultValue={this.state.formValues.radioGroupValue}
                        >
                            <Radio value={1}>A</Radio>
                            <Radio value={2}>B</Radio>
                            <Radio disabled={true} value={3}>C</Radio>
                            <Radio value={4}>D</Radio>
                            <Radio value={5}>E</Radio>
                            <Radio value={6}>F</Radio>
                            <Radio value={7}>G</Radio>
                            <Radio value={8}>H</Radio>
                        </RadioGroup>
                    </Col>
                    <Col span={2}>
                        <label htmlFor="级联选择1" className="infoForm_label" >级联1:</label>
                    </Col>
                    <Col span={4}>
                        <FormItem
                            validateStatus={this.state.validateStatusProvince}
                        >
                            <Select value={this.state.formValues.province} style={{ width: '80%' }} onChange={this.handleProvinceChange} showSearch>
                                {provinceOptions}
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span={2}>
                        <label htmlFor="级联选择2" className="infoForm_label" >级联2:</label>
                    </Col>
                    <Col span={4}>
                        <FormItem
                            validateStatus={this.state.validateStatusCity}
                        >
                            <Select value={this.state.formValues.city} style={{ width: '80%' }} onChange={this.onSecondCityChange} showSearch>
                                {cityOptions}
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span={2}>
                        <label className="infoForm_label" >远程下拉框:</label>
                    </Col>
                    <Col span={4}>
                        <FormItem
                            validateStatus={this.state.validateStatusRemote}
                            style={{paddingRight:'20px'}}
                        >
                            <Select
                            showSearch
                            allowClear
                            value={this.state.formValues.selectRemote}
                            onSearch={this.handleSelectAutoCompleteRemoteSearch}
                            onChange={this.handleSelectAutoCompleteRemoteChange}
                            optionFilterProp="children"
                            style={{height:'33px',width:'100%'}}
                            filterOption={(input, option) => option.props.dataSearchVal.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                          >
                              {selectRemoteChildren}
                          </Select>
                        </FormItem>
                    </Col>
                    <Col span={2}>
                        <label htmlFor='inputNumber' className="infoForm_label" >数字:</label>
                    </Col>
                    <Col span={4}>
                        <FormItem
                            validateStatus={this.state.validateStatusInputNumber}
                            style={{paddingRight:'20px'}}
                        >
                            <Input
                                id='inputNumber'    
                                name='inputNumber'
                                disabled={false}
                                placeholder="请输入"
                                onChange={this.handleInputNumberChange}
                                value={this.state.formValues.inputNumberValue}
                                defaultValue={this.state.formValues.inputNumberValue}
                            />
                        </FormItem>
                    </Col>
                    <Col span={2}>
                        <label htmlFor='email' className="infoForm_label" >email:</label>
                    </Col>
                    <Col span={4}>
                        <FormItem
                            validateStatus={this.state.validateStatusEmail}
                            style={{paddingRight:'20px'}}
                            hasFeedback
                        >
                            <Input
                                id='email'    
                                name='email'
                                disabled={false}
                                placeholder="请输入"
                                onChange={this.handleEmailChange}
                                value={this.state.formValues.email}
                                defaultValue={this.state.formValues.email}
                            />
                        </FormItem>
                    </Col>
                </Row>
                <Row >
                    <Col span={2} offset={10}>
                        <Button type='primary' onClick={this.handleSubmit}>确定</Button>
                    </Col>
                    <Col span={2} >
                        <Button type='default' onClick={this.handResetForm}>清空</Button>
                    </Col>
                </Row>
            </div>
        );
    }
}